package com.crawler.harbour.utils;


import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

public class AESUtil {
	 // js文件
   private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
   static {
	 try {
		    // 执行指定脚本
		engine.eval(new FileReader(AESUtil.class.getResource("/js/xhct_common.min.js").getPath()));
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   }
   
    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);

    private static final String cryptaesURL = "http://tool.chacuo.net/cryptaes";

    public static String cryptaes(String str, String key) {
        String result = "";
        Map<String, Object> data = new HashMap<>();
        data.put("type", "aes");
        data.put("data", str);
        key = DigestUtil.md5Hex(key).substring(0, 16).toUpperCase();
        String arg = "m=cbc_pad=pkcs7_block=128_p=" + key + "_i=" + key + "_o=0_s=gb2312_t=0";
        data.put("arg", arg);
        result = HttpRequest.post(cryptaesURL)
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .form(data)
                .execute()
                .body();
        Map<String, Object> resultMap = JSON.parseObject(result);
        if (resultMap.get("data") != null) {
            str = resultMap.get("data").toString();
            List list = JSON.parseArray(str);
           return list.get(0).toString();
        }
        return  null;
    }
    
    /**
     * 厦门海通船期查询
     * @return
     * @throws Exception
     */
    public static String xhct(String str)  {
    	try {
			return Base64Util.encode(str.getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return "";
    }

    /**
     * 厦门集装箱码头集团
     * @param str  TVVREF_1海天
     * @param pass fnlagjf4sangjcqkslgrfsqn
     * @return
     * @throws Exception
     */
    public static String xhct(String str,String pass)  {
        String result="";
        try {
            if (engine instanceof Invocable) {
                // encrypt，并传入两个参数
                Invocable invoke = (Invocable) engine;
                result = invoke.invokeFunction("encrypt", str, pass).toString();
                LOGGER.info("str = " + str + ",pass = " + pass + ",result = " + result);
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage());
        }
        return  result;
    }
}